<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat, toYuan, copyToCliboard, timeFormat_2 } from '@/hooks/util'
import * as orderApi from '@/api/order'
import { message } from 'ant-design-vue'
import Tip from './components/Tip.vue'
import TipCard from './components/TipCard.vue'
import NB from '@/assets/NB.png'
import CZK from '@/assets/CZK.png'
import Lottie from './components/Lottle.vue'
import * as Animation from '@/assets/lottie/property@2.json'
import * as Animation_1 from '@/assets/lottie/property@1.json'
import AddCard from './components/AddCard.vue'
import * as assetsOrderApi from '@/api/assetsOrder'
import { useUserStore } from '@/store/modules/user'
import BillDetail from './components/BillDetail.vue'

const userStore = useUserStore()
// console.log('userStore=', userStore.userInfo)

const tifRef = ref()
const tipCardRef = ref()
const AddCardRef = ref()
const BillDetailRef = ref()

const route = useRoute()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper?: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  [propName: string]: any
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '类型',
    key: 'type',
    width: 420,
  },
  {
    title: '卡密状态',
    key: 'status',
    width: 260,
  },
  {
    title: '平台账号',
    key: 'robotId',
    width: 400,
  },
  {
    title: '时间信息',
    key: 'createTime',
    width: 300,
    fixed: 'right',
  },
  // {
  //   title: '操作',
  //   key: 'action',
  //   width: 200,
  //   fixed: 'right',
  //   align: 'center',
  // },
]

// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await assetsOrderApi.cardPage(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

// 翻译渠道
const getChannel = (num: string | number) => {
  if (num == 1) {
    return '微信'
  } else if (num == 2) {
    return '企业微信'
  } else if (num == 3) {
    return '闲鱼'
  }
}

onMounted(() => {
  getList()
  cardNum()
  getNbBalnce()
})

import type { SelectProps } from 'ant-design-vue'
const statusList = ref<SelectProps['options']>([
  {
    label: '未使用',
    value: 0,
  },
  {
    label: '已使用',
    value: 2,
  },
])
const channelList = ref<SelectProps['options']>([
  {
    label: '微信',
    value: 1,
  },
  {
    label: '企业微信',
    value: 2,
  },
  {
    label: '闲鱼',
    value: 3,
  },
])

const formRef = ref()
interface FormState {
  code?: string
  phone?: string
  status?: number
  [propName: string]: any
}
const formState = reactive<FormState>({})

// 查询
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    // console.log('formState=', formState)

    if (formState.code) {
      searchParams.value.code = formState.code
    }
    if (formState.phone) {
      searchParams.value.phone = formState.phone
    }
    if (formState.status == 0 || formState.status == 2) {
      searchParams.value.status = formState.status
    }

    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()

  formRef.value.resetFields()
  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }

  getList()
}

const showTip = () => {
  tifRef.value.showModal()
}

const showTipCard = () => {
  tipCardRef.value.showModal()
}

const duihuan = () => {
  AddCardRef.value.showModal()
}

let activeKey = ref<string>('2')
let theCardNum = ref<number>(0)
const cardNum = async () => {
  let params = {
    userId: userStore.userInfo.id,
  }
  try {
    let { state, data, message: msg } = await assetsOrderApi.cardNum(params)
    if (state === 200) {
      // console.log(data)
      theCardNum.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

let ncbalance = ref<number>(0)
const getNbBalnce = async () => {
  let params = {
    userId: userStore.userInfo.id,
  }
  try {
    let { state, data, message: msg } = await assetsOrderApi.nbBalnce(params)
    if (state === 200) {
      // console.log(data)
      ncbalance.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const copyRule = (id: string) => {
  copyToCliboard(id)
}

const theRefresh = () => {
  getNbBalnce()
  getList()
}

const changeTab = () => {
  getList()
  BillDetailRef.value.getList()
}

const copyRuleAll = () => {
  // console.log('批量复制=', selectedRow.value)
  let allStr = ``
  selectedRow.value.map((item: any) => {
    allStr += item.code + '\n'
  })
  // console.log('str=', allStr)
  copyToCliboard(allStr)
  message.success('复制成功')
}
</script>

<template>
  <page-container :title="route.meta.title">
    <div style="display: flex; margin-bottom: 20px">
      <a-card title="账户管理" style="flex: 1; margin-right: 10px">
        <template #extra>
          <a @click="showTip">
            <QuestionCircleOutlined style="font-size: 16px" />
          </a>
        </template>
        <div style="display: flex">
          <div class="leftImg">
            <Lottie :animation-data="Animation_1" />
          </div>

          <div style="margin-left: 10px">
            <div>
              <p style="color: rgba(59, 59, 59, 0.5)">可用余额（￥）</p>
              <span style="margin-left: 10px; font-size: 20px">{{ toYuan(ncbalance) }}</span>
            </div>
            <div style="margin-left: 0px; margin-top: 15px">
              <a-button size="small" disabled>充值</a-button>
              <a-button disabled style="margin: 0 10px" size="small" type="primary">转赠</a-button>
            </div>
          </div>
        </div>
      </a-card>
      <a-card title="卡密管理" style="flex: 1">
        <template #extra>
          <a @click="showTipCard">
            <QuestionCircleOutlined style="font-size: 16px" />
          </a>
        </template>
        <div style="display: flex">
          <div class="leftImg">
            <!-- <img :src="CZK" alt="" /> -->
            <Lottie :animation-data="Animation" />
          </div>

          <div style="margin-left: 10px">
            <div>
              <p style="color: rgba(59, 59, 59, 0.5)">剩余可用（{{ theCardNum }}个）</p>
              <span style="margin-left: 10px; font-size: 20px">0.00</span>
            </div>
            <div style="margin-left: 8px; margin-top: 15px">
              <a-button @click="duihuan" style="margin-right: 10px" size="small" type="primary">
                兑换
              </a-button>
            </div>
          </div>
        </div>
      </a-card>
    </div>

    <a-card style="overflow-x: scroll">
      <a-tabs v-model:activeKey="activeKey" @change="changeTab">
        <a-tab-pane key="1" tab="账单明细">
          <BillDetail ref="BillDetailRef"></BillDetail>
        </a-tab-pane>
        <a-tab-pane key="2" tab="卡密仓库">
          <div class="searchBox">
            <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
              <a-form-item label="卡密" name="code">
                <a-input v-model:value="formState.code" placeholder="卡密" />
              </a-form-item>

              <a-form-item label="手机号" name="phone">
                <a-input v-model:value="formState.phone" placeholder="手机号" />
              </a-form-item>

              <a-form-item label="状态" name="status">
                <a-select
                  v-model:value="formState.status"
                  placeholder="状态"
                  style="width: 150px"
                  allowClear
                >
                  <a-select-option
                    v-for="(item, index) in statusList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item>
                <a-button type="primary" style="border-radius: 6px" @click="search">搜索</a-button>
                <a-button @click="reset" style="border-radius: 6px">重置</a-button>
                <a-dropdown v-if="selectedRowKey.length > 0">
                  <a-button>
                    批量操作
                    <DownOutlined />
                  </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item @click="copyRuleAll">批量复制</a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </a-form-item>
            </a-form>
          </div>
          <div style="margin-bottom: 10px">
            <a-alert :message="'已选择：'+ selectedRowKey.length"  type="info" show-icon />
          </div>
          <a-table
            style="overflow-x: scroll"
            :columns="columns"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            @change="changePage"
            rowKey="id"
            :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }"
            :scroll="{ x: 100 }"
            size="small"
          >
            <template #emptyText>
              <a-empty description="暂无数据" />
            </template>

            <template #headerCell="{ column }">
              <template v-if="column.key === 'id'">
                <span>id</span>
              </template>
            </template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'type'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '80px' }">
                  <a-descriptions-item label="类型">
                    <a-tag color="blue" v-if="record.type == 1">月卡</a-tag>
                    <a-tag color="blue" v-if="record.type == 2">年卡</a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="卡密">
                    {{ record.code }}
                    <a @click="copyRule(record.code)"><CopyOutlined /></a>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'status'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
                  <a-descriptions-item label="状态">
                    <a-tag color="red" v-if="record.status == 2">已使用</a-tag>
                    <a-tag color="blue" v-if="record.status == 0">未使用</a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="使用者手机号">
                    {{ record.phone || '-' }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'robotId'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
                  <a-descriptions-item label="平台账号ID">
                    <span v-if="record.robotId != 0">{{ record.robotId }}</span>
                    <span v-else>-</span>
                  </a-descriptions-item>
                  <a-descriptions-item label="平台账号昵称">
                    {{ record.robotName || '-' }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'createTime'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
                  <a-descriptions-item label="创建时间">
                    {{ timeFormat_2(record.createTime) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="激活时间">
                    {{ timeFormat_2(record.activeTime) }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'action'">
                <div style="width: 180px"></div>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <Tip ref="tifRef"></Tip>
    <TipCard ref="tipCardRef"></TipCard>
    <AddCard ref="AddCardRef" @refresh="theRefresh"></AddCard>
  </page-container>
</template>

<style lang="less" scoped>
@keyframes rotateImage {
  0% {
    transform: rotateY(0deg);
  } /* 初始状态，不旋转 */

  100% {
    transform: rotateY(360deg);
  } /* 末尾状态，旋转一周 */
}

.leftImg {
  width: 120px;
  height: 120px;
  // background: pink;

  img {
    width: 100%;
    height: 100%;
  }

  .animat {
    animation: rotateImage 4s infinite linear;
  }
}

.hiddenText {
  display: inline-block;
  width: 170px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.aTag-seatNo:nth-child(n + 2) {
  margin-top: 3px;
}
.formClass {
  :nth-child(1) {
    margin-bottom: 2px;
  }
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 300px;
  img {
    width: 100%;
  }
}

.robitStatusClass {
  text-align: center;
}
</style>
